<template>
  <el-card shadow="never">
    <template #header>
      <div class="flex-x-between">
        <span>销售趋势</span>
        <div>
          <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
            <el-radio-button label="week">近7天</el-radio-button>
            <el-radio-button label="month">近30天</el-radio-button>
            <el-radio-button label="quarter">近90天</el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </template>

    <div ref="chartRef" :style="{ height }"></div>

    <div class="mt-4 flex-x-between">
      <div class="flex-y-center">
        <div class="i-svg:sales w-4 h-4 mr-1" />
        <span class="text-sm">总销售额：¥{{ totalSales }}</span>
      </div>
      <div class="flex-y-center">
        <div class="i-svg:order w-4 h-4 mr-1" />
        <span class="text-sm">总订单量：{{ totalOrders }}</span>
      </div>
      <div class="flex-y-center">
        <div class="i-svg:customer w-4 h-4 mr-1" />
        <span class="text-sm">客户数：{{ totalCustomers }}</span>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import * as echarts from "echarts";
// import { formatAmount } from "@/utils";
// import { useEventListener } from "@vueuse/core";

const props = defineProps({
  height: {
    type: String,
    default: "400px",
  },
});

const timeRange = ref("week");
const chartRef = ref<HTMLDivElement>();
let chart: echarts.ECharts | null = null;

// 假数据
const totalSales = ref(0);
const totalOrders = ref(0);
const totalCustomers = ref(0);

// 生成随机数据
const generateRandomData = (days: number) => {
  const salesData = [];
  const orderData = [];
  const customerData = [];
  const dateList = [];

  let baseSales = 5000;
  let baseOrders = 30;
  let baseCustomers = 20;

  // 计算总和
  let sumSales = 0;
  let sumOrders = 0;
  let sumCustomers = 0;

  for (let i = 0; i < days; i++) {
    const date = new Date();
    date.setDate(date.getDate() - (days - 1 - i));
    dateList.push(`${date.getMonth() + 1}/${date.getDate()}`);

    // 生成波动数据
    const sales = baseSales + Math.round(Math.random() * 3000 - 1000);
    const orders = baseOrders + Math.round(Math.random() * 10 - 5);
    const customers = baseCustomers + Math.round(Math.random() * 8 - 4);

    salesData.push(sales);
    orderData.push(orders);
    customerData.push(customers);

    sumSales += sales;
    sumOrders += orders;
    sumCustomers += customers;

    // 基础值每天略有变化
    baseSales += Math.round(Math.random() * 500 - 250);
    baseOrders += Math.round(Math.random() * 3 - 1);
    baseCustomers += Math.round(Math.random() * 2 - 1);

    // 确保基础值不会太低
    baseSales = Math.max(3000, baseSales);
    baseOrders = Math.max(15, baseOrders);
    baseCustomers = Math.max(10, baseCustomers);
  }

  totalSales.value = sumSales;
  totalOrders.value = sumOrders;
  totalCustomers.value = sumCustomers;

  return { dateList, salesData, orderData, customerData };
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  chart = echarts.init(chartRef.value);
  updateChart();
};

// 更新图表数据
const updateChart = () => {
  if (!chart) return;

  const days = timeRange.value === "week" ? 7 : timeRange.value === "month" ? 30 : 90;
  const { dateList, salesData, orderData, customerData } = generateRandomData(days);

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
    },
    legend: {
      data: ["销售额", "订单量", "客户数"],
      right: 10,
      top: 0,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        data: dateList,
        axisLabel: {
          interval: Math.ceil(days / 10) - 1, // 控制显示密度
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        name: "销售额(元)",
        position: "left",
        axisLabel: {
          formatter: "¥{value}",
        },
      },
      {
        type: "value",
        name: "数量",
        position: "right",
        splitLine: {
          show: false,
        },
      },
    ],
    series: [
      {
        name: "销售额",
        type: "line",
        smooth: true,
        lineStyle: {
          width: 3,
          color: "#5b8ff9",
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "rgba(91, 143, 249, 0.5)",
            },
            {
              offset: 1,
              color: "rgba(91, 143, 249, 0.1)",
            },
          ]),
        },
        emphasis: {
          focus: "series",
        },
        data: salesData,
      },
      {
        name: "订单量",
        type: "line",
        smooth: true,
        yAxisIndex: 1,
        lineStyle: {
          width: 3,
          color: "#5ad8a6",
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "rgba(90, 216, 166, 0.5)",
            },
            {
              offset: 1,
              color: "rgba(90, 216, 166, 0.1)",
            },
          ]),
        },
        emphasis: {
          focus: "series",
        },
        data: orderData,
      },
      {
        name: "客户数",
        type: "line",
        smooth: true,
        yAxisIndex: 1,
        lineStyle: {
          width: 3,
          color: "#f6bd16",
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "rgba(246, 189, 22, 0.5)",
            },
            {
              offset: 1,
              color: "rgba(246, 189, 22, 0.1)",
            },
          ]),
        },
        emphasis: {
          focus: "series",
        },
        data: customerData,
      },
    ],
  };

  chart.setOption(option);
};

// 时间范围变化
const handleTimeRangeChange = () => {
  updateChart();
};

// // 窗口大小变化时重绘图表
// useEventListener("resize", () => {
//   chart?.resize();
// });

onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  chart?.dispose();
});
</script>

<style lang="scss" scoped>
// 可以添加自定义样式
</style>
